const $submit = $('.js-submit');
const $clear = $('.js-clear');
const $input = $('.input');
const $logs = $('.logs');
let logs = [];
const key = 'magic-time-logger';

init();

function init() {
    const cachedLogs = store.get(key);
    if (cachedLogs && cachedLogs.length > 0) {
        logs = cachedLogs;
        render();
    }

    $submit.addEventListener('click', onSubmit);
    $clear.addEventListener('click', onClear);
    $input.addEventListener('keydown', onKeyDown);
}

function onKeyDown(e) {
    if (e.keyCode === 13) {
        onSubmit();
        e.target.blur();
    }
}

function onSubmit() {
    const val = $input.value;
    const ts = Date.now();

    const newLog = {
        begin: ts,
        event: val,
    }

    if (checkValid(newLog) === false) return;

    addLog(newLog);
    clearInput();
}

function clearInput() {
    $input.value = '';
}

function onClear() {
    const confirmed = window.confirm('删除所有时间记录？');
    if (!confirmed) return;

    store.remove(key);
    logs = [];
    render();
    $logs.innerHTML = 'You have cleared all your logs';
}

function checkValid(log) {
    if (!log) {
        alert('Log should not be empty');
        return false;
    }

    const {
        event,
    } = log;

    if (!event || !event.trim()) {
        alert('event should not be empty!');
        return false;
    }

    return true;
}

function addLog(newLog) {
    console.log('add log', newLog);
    logs.push(newLog);
    store.set(key, logs);
    render();
}

function render() {
    let s = '';
    for (let i = logs.length - 1; i >= 0; i--) {
        const log = logs[i];
        // debugger;
        const { begin, event } = log;
        const beginTime = getTime(begin);
        let end = Date.now();
        if (i < logs.length - 1) {
            end = logs[i+1].begin;
        }
        const diff = end - begin;
        const diffTime = getDiffTime(diff);

        s += `<div class="cell">
                <div class="cell__hd">${beginTime}</div>
                <div class="cell__bd">${event}</div>
                <div class="cell__ft">${diffTime}</div>
            </div>`;
    }

    $logs.innerHTML = s;
}

function p(n) {
    if (n >= 10) return n + '';
    return '0' + n;
}